﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace ShiQuan.SocketHelper
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //更新更新程序
            try
            {
                //
                string mSourcePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content\\AppUpdater");
                if (System.IO.Directory.Exists(mSourcePath))
                {
                    string mDestPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppUpdater");
                    if (System.IO.Directory.Exists(mDestPath) == false)
                        System.IO.Directory.CreateDirectory(mDestPath);
                    /*判断更新进程是否关闭*/
                    if (ExistsProcess("ShiQuan.AppUpdater"))
                    {
                        MessageBox.Show("ShiQuan.AppUpdater 正在运行！");
                    }
                    else
                    {
                        string[] files = System.IO.Directory.GetFiles(mSourcePath);
                        for (int index = 0; index < files.Length; index++)
                        {
                            string fileName = System.IO.Path.GetFileName(files[index]);
                            string saveFile = System.IO.Path.Combine(mDestPath, fileName);
                            System.IO.File.Copy(files[index], saveFile, true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("更新更新程序异常：" + ex.ToString());
                return;
            }
            //检查更新
            new Thread(m =>
            {
                string fileName = System.IO.Path.Combine(Application.StartupPath, "AppUpdater\\ShiQuan.AppUpdater.exe");
                if (System.IO.File.Exists(fileName))
                {
                    ProcessStartInfo processInfo = new ProcessStartInfo();
                    processInfo.Arguments = "AppPath=" + Application.StartupPath;
                    processInfo.FileName = fileName;
                    Process.Start(processInfo);
                }

            }).Start();

            Application.Run(new FrmMain());
        }

        /// <summary>
        /// 判断进程是否存在
        /// </summary>
        /// <param name="processName"></param>
        /// <returns></returns>
        public static bool ExistsProcess(string processName)
        {
            Process[] process = Process.GetProcessesByName(processName);
            return (process != null && process.Length > 0);
        }
    }
}
